import React from 'react';
import { Button } from 'antd';
import { PlusOutlined, PlusCircleOutlined, DeleteOutlined } from '@ant-design/icons';
import { isEqual } from 'lodash';

import { removeRuleGroup } from '../../store/actions';
import { Action, Config } from '../../types';
import { addGroup, addRule } from '../../store/actions';
import { uuid } from '../../utils';

const RuleGroupActions: React.FC<{
  config: Config,
  path: string,
  onClick: (action: Action) => void,
}> = React.memo((props) => {
  const { config, path, onClick } = props;

  const renderDel = () => {
    return (
      <Button
        size={config.settings.size}
        icon={<DeleteOutlined />}
        type="default"
        onClick={() => onClick(removeRuleGroup(path))}
      >
        {config.settings.delGroupLabel}
      </Button>
    );
  }

  const renderAddRule = () => {
    return (
      <Button
        size={config.settings.size}
        icon={<PlusOutlined />}
        onClick={() => {
          onClick(
            addRule({
              id: void 0,
              field: void 0,
              type: void 0,
              input: void 0,
              operator: void 0,
              value: void 0,
              path: uuid()
            }, path)
          );
        }}
      >
        {config.settings.addRuleLabel}
      </Button>
    );
  }

  const renderAddGroup = () => {
    return (
      <Button
        size={config.settings.size}
        icon={<PlusCircleOutlined />}
        onClick={() => {
          onClick(
            addGroup({
              condition: "AND",
              not: false,
              rules: [
                {
                  id: void 0,
                  field: void 0,
                  type: void 0,
                  input: void 0,
                  operator: void 0,
                  value: void 0,
                  path: uuid()
                }
              ],
              path: uuid()
            }, path)
          );
        }}
      >
        {config.settings.addGroupLabel}
      </Button>
    );
  }

  return (
    <>
      {!config.settings.readonly && config.settings.showActions && (
        <Button.Group>
          {config.settings.showAddRule && renderAddRule()}
          {config.settings.showAddGroup && renderAddGroup()}
          {config.settings.showDelGroup && renderDel()}
        </Button.Group>
      )}
    </>
  );
}, (prevProps, nextProps) => {
  return isEqual(nextProps.config, prevProps.config);
});

export default RuleGroupActions;
